package controllers

import (
	"github.com/astaxie/beego"
	"strconv"
	"time"
	"yunshangxiaozhao/models"
	"yunshangxiaozhao/utils"
)

const (
	AccessKeyID     = "LTAI4Fn1AnpeKLucEfh247jA"
	AccessKeySecret = "T0kYwcHBCvxTy6ADzRYa6D5sO8viuu"

	DomainName     = "live.kernelylz.cn"
	AppName        = "yunxiaozhao" // 自己生成
	PullPrivateKey = "DNDprivateKey"
	PushPrivateKey = "DNDprivateKey"

	PullEndpoint = "inlive.kernelylz.cn"
)

// Operations about Company
type LiveController struct {
	beego.Controller
}

func (l *LiveController) RetData(resp map[string]interface{}) {
	l.Data["json"] = resp
	l.ServeJSON()
}

// @Title GetLiveList
// @Description get live by company id
// @Param	company_id	path	int	true	"The id of company"
// @Success 200 {object} models.Live
// @Failure 400 :body is empty
// @router /company/:company_id [get]
func (l *LiveController) GetLiveByCompanyId() {
	resp := make(map[string]interface{})
	var companyId, err = l.GetInt(":company_id")
	if err != nil {
		l.Abort("ParamIsEmpty")
	}
	live, err := models.GetLiveByCompanyId(companyId)
	if err != nil {
		l.Abort("GetDataFail")
	} else {
		resp["code"] = 200
		resp["data"] = live
		resp["msg"] = "获取直播数据成功"
	}
	l.RetData(resp)
}

// @Title GetLive
// @Description get live by company id
// @Param	id	path	int	true	"The id of live"
// @Success 200 {object} models.Live
// @Failure 400 :body is empty
// @router /:id [get]
func (l *LiveController) GetLiveById() {
	resp := make(map[string]interface{})
	var id, err = l.GetInt(":id")
	if err != nil {
		l.Abort("ParamIsEmpty")
	}
	live, err := models.GetLiveById(id)
	if err != nil {
		l.Abort("GetDataFail")
	} else {
		resp["code"] = 200
		resp["data"] = live
		resp["msg"] = "获取直播数据成功"
	}
	l.RetData(resp)
}

// @Title GetLiveByKeyword
// @Description 直播搜索接口（P20）
// @Param	keyword	query	string	true	"The keyword to search"
// @Param	page	query 	int	true	"The page of live table(the index start with 0)"
// @Param	limit	query 	int	true	"The limit number of live table"
// @Success 200 {object} models.Live
// @Failure 400 :body is empty
// @router /search [get]
func (l *LiveController) GetLiveByKeyword() {
	resp := make(map[string]interface{})
	page, err1 := l.GetInt("page")
	limit, err2 := l.GetInt("limit")
	keyword := l.GetString("keyword")
	if err2 != nil || err1 != nil || keyword == "" {
		l.Abort("ParamIsEmpty")
	}
	list, err := models.GetLiveListByKeyword(keyword, page, limit)
	list, err = models.GetLiveListCompany(list)
	if err != nil {
		l.Abort("GetDataFail")
	} else {
		resp["code"] = 200
		resp["data"] = list
		resp["msg"] = "获取直播数据成功"
	}
	l.RetData(resp)
}

// @Title GetPushLive
// @Description 获取直播推流地址
// @Param	id	query	int	true	"id of live"
// @Param	timeout	query	int	true	"直播时长(单位为半小时)"
// @Success 200 {object} models.Live
// @Failure 400 live not found
// @router /live/push [get]
func (l *LiveController) GetPushLive() {
	resp := make(map[string]interface{})
	var live models.Live
	id, err := l.GetInt("id")
	timeout, err := l.GetInt("timeout")
	if err != nil {
		l.Abort("ParamIsEmpty")
	}
	timestamp := getEndTimestamp(time.Now().Unix(), timeout)
	streamName := utils.GenerateStreamName(id)
	strPush := "/" + AppName + "/" + streamName + "-" + timestamp + "-0-0-" + PushPrivateKey
	strPull := "/" + AppName + "/" + streamName + ".flv" + "-" + timestamp + "-0-0-" + PullPrivateKey

	data := make(map[string]interface{})
	data["PushUrl"] = "rmtp://" + DomainName + "/" + AppName + "/" + streamName + "?auth_key=" + timestamp + "-0-0-" + utils.Md5Encode(strPush)

	live.Company, err = models.GetCompanyById(id)
	live.Url = "http://" + PullEndpoint + "/" + AppName + "/" + streamName + ".flv" + "?auth_key=" + timestamp + "-0-0-" + utils.Md5Encode(strPull)
	err = models.UpdateCompanyLive(live)
	if err != nil {
		l.Abort("LiveCreate")
	}
	resp["data"] = data
	l.RetData(resp)
}

// @Title GetPullLive
// @Description 获取直播地址
// @Param	id	query	int	true	"id of company"
// @Success 200 {object} models.Live
// @Failure 400 live not found
// @router /live/pull [get]
func (l *LiveController) GetPullLive() {
	resp := make(map[string]interface{})
	id, err := l.GetInt("id")

	live, err := models.GetLiveByCompanyId(id)
	if err != nil {
		l.Abort("LiveNotFound")
	}

	resp["data"] = live
	l.RetData(resp)
}

/*
 获取直播推流结束的 timestamp
*/
func getEndTimestamp(time int64, timeout int) string {
	intTime := int(time) + timeout*30*60

	return strconv.Itoa(intTime)
}
